﻿using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using DBUtility;
using gfLibrary;
using IYAKASAPortal.Services;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;
using UtilityHelper;

namespace IYAKASAPortal.PrintAll
{
    public partial class PrintAJ : System.Web.UI.Page
    {

        private UserInfo userInfo { get; set; }
        private ReportDocument document;
        private List<string> m_lstMotorType;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.m_lstMotorType = new List<string>();
            this.m_lstMotorType.Add("07");
            this.m_lstMotorType.Add("08");
            this.m_lstMotorType.Add("09");
            this.m_lstMotorType.Add("10");
            this.m_lstMotorType.Add("11");
            this.m_lstMotorType.Add("12");
            this.m_lstMotorType.Add("17");
            this.m_lstMotorType.Add("19");
            this.m_lstMotorType.Add("21");
            this.m_lstMotorType.Add("24");
            if (!IsPostBack)
            {
                ShowBtnWitnLiceNo(btnUpload, "08,");
                ShowBtnWitnLiceNo(btnReCheck,"08,");
                ShowBtnWitnLiceNo(btnSave,"08");
                

                if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
                {
                    BindReportData(Request["UniqueKey"].ToString());
                }
                else
                {
                    gfJs.RunFunction(this.Page, "parent.window.location = '../logout.aspx';");
                }
            }

            RESULT_VEHICLE_INFO_BLL BLL = new RESULT_VEHICLE_INFO_BLL();
            var INFO = BLL.GetModelList("ID=" + Request["UniqueKey"].ToString());
            string AJLSH = INFO[0].JCLSH;
            txtAJLSH.Value = AJLSH;

            if (INFO[0].JCXH == 5)
            {
                ShowBtnWitnLiceNo(btnReCheckMoto, "15,");
            }


        }


        /// <summary>
        /// 根据权限编号显示按钮
        /// </summary>
        /// <param name="btn"></param>
        /// <param name="licenseNo"></param>
        private void ShowBtnWitnLiceNo(Button btn, string licenseNo)
        {
            try
            {
                if (Session["UserName"] != null && Session["UserName"].ToString() != "")
                {
                    string userName = Session["UserName"].ToString();
                    userInfo = IYAKASAPortal.Services.UserAuthority.GetUserAuthority(userName);
                    if (userInfo.UserRole.Contains(licenseNo))
                    {
                        btn.Visible = true;
                    }
                    else
                    {
                        btn.Visible = false;
                    }
                }
                else
                {
                    gfJs.RunFunction(this.Page, "parent.window.location = '../logout.aspx';");
                }
            }
            catch (Exception ex)
            { 
            }

        }
        

        protected override void OnInit(EventArgs e)
        {
            if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
            {
                BindReportData(Request["UniqueKey"].ToString());
            }
        }

        private void BindReportData(string strKey)
        {
            
            string strPath = Server.MapPath("~/rpt/CrystalReportAJ.rpt");
            bool bSingle = chkSingle.Checked;

            SetCRDataSource setData = new SetCRDataSource();
            document = setData.BindAJReportEx(strKey, strPath, bSingle);
            CRAJ.ReportSource = document;
            CRAJ.DataBind();
            CRAJ.RefreshReport();

            CONST_DEFINE_WEB_BLL bll = new CONST_DEFINE_WEB_BLL();
            var constInfos = bll.GetModelList("CategoryID=5 order by SeqNumber");

            ListItem oItem;
            chkSuggest.Items.Clear();
            foreach (var v in constInfos)
            {
                oItem = new ListItem() { Text = v.Remark, Value = v.ID.ToString() };
                chkSuggest.Items.Add(oItem);
            }

            BGD_SUGGEST_BLL bgd_bll = new BGD_SUGGEST_BLL();
            RESULT_VEHICLE_INFO_BLL vehicleInfo = new RESULT_VEHICLE_INFO_BLL();
            string strJCLSH = vehicleInfo.GetModelList("ID=" + strKey.ToString())[0].JCLSH;

            var bgd = bgd_bll.GetModelList("JCLSH='" + strJCLSH + "' and SingleFlag='" + bSingle + "'");
            if (bgd.Length > 0)
            {
                if (!string.IsNullOrEmpty(bgd[0].SuggestItems))
                {
                    string strValues = bgd[0].SuggestItems;
                    CONST_DEFINE_WEB_BLL web_bll = new CONST_DEFINE_WEB_BLL();
                    strValues = strValues.Substring(0, strValues.Length - 1);
                    if (strValues.Contains(","))
                    {
                        string[] lst = strValues.Split(',');

                        for (int i = 0; i < chkSuggest.Items.Count; i++)
                        {
                            foreach (var v in lst)
                            {
                                if (chkSuggest.Items[i].Value == v)
                                {
                                    chkSuggest.Items[i].Selected = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < chkSuggest.Items.Count; i++)
                        {
                            chkSuggest.Items[i].Selected = (chkSuggest.Items[i].Value == strValues);
                        }
                    }
                }
            }
        }

        protected void btnRG_Click(object sender, EventArgs e)
        {
            if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
            {
                Response.Redirect("PrintAJRG.aspx?UniqueKey=" + Request["UniqueKey"].ToString());
            }
            else
            {
                gfJs.RunFunction(this.Page, "parent.window.location = '../logout.aspx';");
            }
        }

        protected void btnYQ_Click(object sender, EventArgs e)
        {
            RESULT_VEHICLE_INFO_BLL BLL = new RESULT_VEHICLE_INFO_BLL();
            var INFO = BLL.GetModelList("ID=" + Request["UniqueKey"].ToString());
            string CLZLDH = INFO[0].CLZLDH.Trim();
            if (CLZLDH != "")
            {
                if (this.m_lstMotorType.Contains(INFO[0].HPZLDH))
                {
                    if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
                    {
                        Response.Redirect("PrintAJMotor.aspx?UniqueKey=" + Request["UniqueKey"].ToString());
                    }
                    else
                    {
                        gfJs.RunFunction(this.Page, "parent.window.location = '../logout.aspx';");
                    }
                }
                else
                {
                    if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
                    {
                        Response.Redirect("PrintAJYQ.aspx?UniqueKey=" + Request["UniqueKey"].ToString());
                    }
                    else
                    {
                        gfJs.RunFunction(this.Page, "parent.window.location = '../logout.aspx';");
                    }
                }
            }
        }

        protected void btnAJ_Click(object sender, EventArgs e)
        {
            if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
            {
                BindReportData(Request["UniqueKey"].ToString());
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string strJCLSH = "";
                if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
                {
                    RESULT_VEHICLE_INFO_BLL vehicleInfo = new RESULT_VEHICLE_INFO_BLL();
                    strJCLSH = vehicleInfo.GetModelList("ID=" + Request["UniqueKey"].ToString())[0].JCLSH;
                }
                string strAJ_SUG = "";
                for (int i = 0; i < chkSuggest.Items.Count; i++)
                {
                    if (chkSuggest.Items[i].Selected)
                    {
                        strAJ_SUG += chkSuggest.Items[i].Value + ",";
                    }
                }


                bool bSingle = chkSingle.Checked;
                BGD_SUGGEST_BLL bll = new BGD_SUGGEST_BLL();
                var bgd = bll.GetModelList("JCLSH='" + strJCLSH + "' and SingleFlag='" + bSingle + "'");

                BGD_SUGGEST sug = new BGD_SUGGEST();
                if (bgd.Length > 0)
                {
                    sug = bgd[0];
                    sug.SuggestItems = strAJ_SUG;
                    sug.SugNextEndTime = txtEndDate.Text.Trim();
                    sug.SugNextStartTime = txtStartDate.Text.Trim();

                    bool bUpdate = bll.Update(sug, sug.ID);
                    if (bUpdate)
                    {
                        gfAjaxJs.SetAlertMsg(this.UpdatePanel1, "保存成功！");
                        BindReportData(Request["UniqueKey"].ToString());
                    }
                    else
                    {
                        gfAjaxJs.SetAlertMsg(this.UpdatePanel1, "保存失败！");
                        return;
                    }
                }
                else
                {
                    sug.ID = bll.GetMax_ID();
                    sug.SuggestItems = strAJ_SUG;
                    sug.SingleFlag = bSingle;
                    sug.JCLSH = strJCLSH;
                    sug.SugNextStartTime = txtStartDate.Text.Trim();
                    sug.SugNextEndTime = txtEndDate.Text.Trim();
                    if (bll.Insert(sug))
                    {
                        gfAjaxJs.SetAlertMsg(this.UpdatePanel1, "保存成功！");
                        BindReportData(Request["UniqueKey"].ToString());
                    }
                    else
                    {
                        gfAjaxJs.SetAlertMsg(this.UpdatePanel1, "保存失败！");
                        return;
                    }
                }

            }
            catch (Exception ex)
            {
            }
        }

        protected void chkSingle_CheckedChanged(object sender, EventArgs e)
        {
            btnAJ_Click(sender, e);
        }

        protected override void OnUnload(EventArgs e)
        {
            if (document != null)
            {
                document.Dispose();
            }
            base.OnUnload(e);
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string strJCLSH = "";
            if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
            {
                RESULT_VEHICLE_INFO_BLL vehicleInfo = new RESULT_VEHICLE_INFO_BLL();
                strJCLSH = vehicleInfo.GetModelList("ID=" + Request["UniqueKey"].ToString())[0].JCLSH;

                UploadNetInfos uploadInfo = new UploadNetInfos();
                string userName = Session["UserName"].ToString();
                userInfo = IYAKASAPortal.Services.UserAuthority.GetUserAuthority(userName);

                bool bUpload = uploadInfo.UploadNetInformation(strJCLSH, userInfo.UserName);

                string str = string.Empty;
                if (bUpload)
                {
                    str = @"layer.confirm('上传总结论成功，<br/>是否关闭当前页面？', {
                         time:0,
                         icon:1,
                         btn: ['确定','取消'],
                            success: function(layero, index) {
                                this.enterEsc = function(event) {
                                    if (event.keyCode === 13) {
                                          $(document).off('keydown', this.enterEsc);                                         
                                         window.close();
                                         
                                         }
                                    };
                                $(document).on('keydown', this.enterEsc); 
                            },
                            end: function() {
                                 $(document).off('keydown', this.enterEsc); //解除键盘关闭事件
                                }
                            }, function(){
                              window.close();
                            }, function(){

                            }
                            );";                           
                }
                else
                {
                    str = @"layer.confirm('上传总结论失败，<br/>是否关闭当前页面？', {
                         time:0,
                         icon:2,
                         btn: ['确定','取消'],
                            success: function(layero, index) {
                                this.enterEsc = function(event) {
                                    if (event.keyCode === 13) {
                                          $(document).off('keydown', this.enterEsc);                                         
                                         window.close();
                                         
                                         }
                                    };
                                $(document).on('keydown', this.enterEsc); 
                            },
                            end: function() {
                                 $(document).off('keydown', this.enterEsc); //解除键盘关闭事件
                                }
                            }, function(){
                              window.close();
                            }, function(){

                            }
                            );"; 
                }
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "uuu", str, true);
            }
        }

        /// <summary>
        /// 把数据异常的报告单的总判定改为 不合格 再上传
        /// </summary>
        /// <param name="strJCLSH"></param>
        /// <returns></returns>
        private bool AlterZ_PD(string strJCLSH)
        {
            bool succ = false;
            string strSQL =  string.Format("UPDATE RESULT_VEHICLE_INFO SET Z_PD = 2 WHERE JCLSH = '{0}'  ",strJCLSH);
            succ = DbHelper.ExecuteSql(strSQL);
            return succ;
        }

        private void UploadResult(string strJCLSH)
        {
            string strEmployee = string.Empty;
            EMPLOYEE_USER_BLL employeeBll = new EMPLOYEE_USER_BLL();
            var employeeInfo = employeeBll.GetModelList("LICENSE_NAME LIKE '%08,%'");
            if (employeeInfo.Length > 0)
            {
                strEmployee = employeeInfo[0].EMPLOYEE_NAME;
            }

            UploadNetInfos uploadInfo = new UploadNetInfos();
            string userName = Session["UserName"].ToString();
            userInfo = IYAKASAPortal.Services.UserAuthority.GetUserAuthority(userName);

            bool bUpload = uploadInfo.UploadNetInformation(strJCLSH, strEmployee);

            string str = string.Empty;
            if (bUpload)
            {
                str = @"layer.confirm('重检成功，<br/>是否关闭当前页面？', {
                         time:0,
                         icon:1,
                         btn: ['确定','取消'],
                            success: function(layero, index) {
                                this.enterEsc = function(event) {
                                    if (event.keyCode === 13) {
                                          $(document).off('keydown', this.enterEsc);                                         
                                         window.close();
                                         
                                         }
                                    };
                                $(document).on('keydown', this.enterEsc); 
                            },
                            end: function() {
                                 $(document).off('keydown', this.enterEsc); //解除键盘关闭事件
                                }
                            }, function(){
                              window.close();
                            }, function(){

                            }
                            );"; 
            }
            else
            {
                str = @"layer.confirm('重检失败，<br/>是否关闭当前页面？', {
                         time:0,
                         icon:2,
                         btn: ['确定','取消'],
                            success: function(layero, index) {
                                this.enterEsc = function(event) {
                                    if (event.keyCode === 13) {
                                          $(document).off('keydown', this.enterEsc);                                         
                                         window.close();
                                         
                                         }
                                    };
                                $(document).on('keydown', this.enterEsc); 
                            },
                            end: function() {
                                 $(document).off('keydown', this.enterEsc); //解除键盘关闭事件
                                }
                            }, function(){
                              window.close();
                            }, function(){

                            }
                            );";
            }
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "uuu", str, true);

        }

        protected void btnReCheck_Click(object sender, EventArgs e)
        {
            string strJCLSH = "";
            if (Request["UniqueKey"] != null && Request["UniqueKey"].ToString() != "")
            {
                RESULT_VEHICLE_INFO_BLL vehicleInfo = new RESULT_VEHICLE_INFO_BLL();
                strJCLSH = vehicleInfo.GetModelList("ID=" + Request["UniqueKey"].ToString())[0].JCLSH;
                AlterZ_PD(strJCLSH);
                UploadResult(strJCLSH);              
            }
        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                string strUniqueKey = Request["UniqueKey"];
                if ((strUniqueKey == null) || (strUniqueKey.Length == 0) || (gfValidate.Is_Integer(strUniqueKey) == false))
                {                   
                    return;
                }
                RESULT_VEHICLE_INFO_BLL bll = new RESULT_VEHICLE_INFO_BLL();
                RESULT_VEHICLE_INFO[] entitys = bll.GetModelList("ID = " + strUniqueKey);
                if (entitys.Length > 0)
                {
                    bool IsMTC = IYAKASAPortal.Statistics.StaInfoTools.GetIsMTC(entitys[0].CLZLDH);
                    string strContent = string.Empty;
                    if (IsMTC)
                    {
                        strContent = "window.open('" + string.Format("PrintAuto_MotorYQ.aspx?Key={0}", strUniqueKey) + "');";
                    }
                    else
                    {
                        strContent = "window.open('" + string.Format("PrintAuto_AJYQ.aspx?Key={0}", strUniqueKey) + "');";
                    }

                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "uuu", strContent, true);
                }
            }
            catch (Exception ex)
            {

            }
        }

        
    }
}